﻿using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using System.Web;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.Threading.Tasks;

namespace Infrastructure.Controllers
{
    public class ApiControllerBase:ControllerBase
    {
        protected virtual async Task CheckFormParam(object paramObj)
        {
            
        }

        protected async Task<(string, string)> ExportExcelMiniAsync<T>(List<T> list, string sheetName, string fileName)
        {
            IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
            string sFileName = $"{fileName}_{DateTime.Now:MMdd_HHmmss}.xlsx";
            string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName);

            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

            await MiniExcel.SaveAsAsync(fullPath, list, sheetName: sheetName);
            return (sFileName, fullPath);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="path">完整文件路径</param>
        /// <param name="fileName">带扩展文件名</param>
        /// <returns></returns>
        protected IActionResult ExportExcel(string path, string fileName)
        {
            if (!Path.Exists(path))
            {
                throw new CustomException(fileName + "文件不存在");
            }
            var stream = System.IO.File.OpenRead(path);
            Response.Headers.Append("Access-Control-Expose-Headers", "Content-Disposition");
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", HttpUtility.UrlEncode(fileName));
        }
    }
}
